<template>
	<el-card>
		<el-form ref="queryFormRef" :inline="true" :model="state.queryForm" @keyup.enter="getDataList">
			<el-row>
				<el-col :span="8">
					<el-form-item prop="customerName" label="ClientName 客户名字">
						<el-input v-model="state.queryForm.customerName" placeholder=""></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item prop="customerMobile" label="TEL 电话号码">
						<el-input v-model="state.queryForm.customerMobile" placeholder=""></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item prop="market" label="Market 市场">
						<el-input v-model="state.queryForm.market" placeholder=""></el-input>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="8">
					<el-form-item prop="salesName" label="Sales 销售">
						<el-select v-model="state.queryForm.salesId"
						filterable clearable placeholder="please input a keyword">
							<el-option
							v-for="item in salesOptions"
							:key="item.id"
							:label="item.realName"
							:value="item.id"
							/>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item prop="csName" label="CS 客服">
						<el-select v-model="state.queryForm.csId"
						filterable clearable placeholder="please input a keyword">
							<el-option
							v-for="item in csOptions"
							:key="item.id"
							:label="item.realName"
							:value="item.id"
							/>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="8">
					<el-form-item prop="shopNo" label="shopNo 店铺">
						<el-input v-model="state.queryForm.shopNo" placeholder=""></el-input>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row>
				<el-col :span="8">
					<el-form-item prop="business" label="Business 生意">
						<el-input v-model="state.queryForm.business" placeholder=""></el-input>
					</el-form-item>
				</el-col>
				<el-col :span="16">
					<el-form-item>
						<el-button type="primary" @click="getDataList()">查询</el-button>
						<el-button type="default" @click="resetForm()">重置</el-button>
					</el-form-item>
					<el-form-item>
						<el-button type="success" @click="addOrUpdateHandle()">ADD新增</el-button>
					</el-form-item>
					<el-form-item v-auth="'client:delete'">
						<el-button type="danger" @click="deleteBatchHandle()">Delete删除</el-button>
					</el-form-item>
					<el-form-item>
						<el-button type="info" @click="downloadDialog.downloadVisible = true;">ShipmentsDownload出货量下载</el-button>
					</el-form-item>
				</el-col>
			</el-row>
		</el-form>
		<el-table
			v-loading="state.dataListLoading"
			:data="state.dataList"
			border
			style="width: 100%"
			@selection-change="selectionChangeHandle"
			@sort-change="sortChangeHandle"
		>
			<el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
			<el-table-column prop="name" label="Client Name 客户名字" header-align="center" align="center"> </el-table-column>
			<el-table-column prop="mobile" label="Phone Number 电话号码" header-align="center" align="center" width="140"></el-table-column>
			<el-table-column prop="market" label="Market 市场" header-align="center" align="center"></el-table-column>
			<el-table-column prop="business" label="Business  生意" header-align="center" align="center"></el-table-column>
			<el-table-column prop="salesName" label="Ghana Sales 加纳销售" header-align="center" align="center"></el-table-column>
			<el-table-column prop="csName" label="Ghana CS 加纳客服" header-align="center" align="center"></el-table-column>
			<el-table-column prop="shopNo" label="SHOP NO. 店铺号码" header-align="center" align="center"></el-table-column>
			<!-- <el-table-column prop="sort" label="排序" sortable="custom" header-align="center" align="center"></el-table-column> -->
			<!-- <el-table-column prop="createTime" label="创建时间" header-align="center" align="center" width="180"></el-table-column> -->
			<el-table-column label="Operation 操作" fixed="right" header-align="center" align="center" width="170">
				<template #default="scope">
					<el-button type="primary" link @click="addOrUpdateHandle(scope.row.id)">Update修改</el-button>
					<el-button type="primary" link @click="followDateHandle(scope.row.id)">FollowUp跟进日报</el-button>
					<el-button v-auth="'client:delete'" type="primary" link @click="deleteBatchHandle(scope.row.id)">Delete删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<el-pagination
			:current-page="state.page"
			:page-sizes="state.pageSizes"
			:page-size="state.limit"
			:total="state.total"
			layout="total, sizes, prev, pager, next, jumper"
			@size-change="sizeChangeHandle"
			@current-change="currentChangeHandle"
		>
		</el-pagination>
		<!-- 新增 / 修改 -->
		<add-or-update ref="addOrUpdateRef" @refreshDataList="getDataList"></add-or-update>
		<!-- 跟进日报 -->
		<follow-date ref="followDateRef"></follow-date>
		<!-- 出货量下载 -->
		<el-dialog
			v-model="downloadDialog.downloadVisible"
			title="Download"
			width="50%"
			:before-close="handleDownloadClose"
		>
			<el-form ref="dialogRef" :model="downloadDialog" :inline="true">
				<el-form-item prop="createTime" label="CreateTime 创建时间" required>
					<!-- <el-date-picker
						v-model="downloadDialog.createTime"
						type="monthrange"
						unlink-panels
						range-separator="To"
						start-placeholder="Start month"
						end-placeholder="End month"
						:shortcuts="shortcuts"
						value-format="YYYY-MM-DD HH:mm:ss"
						@change="changeCreateTime"
					/> -->
					<el-date-picker
						v-model="downloadDialog.createTime"
						type="month"
						placeholder="Pick a month"
						value-format="YYYY-MM-DD HH:mm:ss"
					/>
				</el-form-item>
				<el-form-item prop="salesName" label="Sales 销售">
					<el-select v-model="downloadDialog.salesId"
					filterable clearable placeholder="please input a keyword">
						<el-option
						v-for="item in salesOptions"
						:key="item.id"
						:label="item.realName"
						:value="item.id"
						/>
					</el-select>
				</el-form-item>
				<el-form-item prop="csName" label="CS 客服">
					<el-select v-model="downloadDialog.csId"
					filterable clearable placeholder="please input a keyword">
						<el-option
						v-for="item in csOptions"
						:key="item.id"
						:label="item.realName"
						:value="item.id"
						/>
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer>
			<span class="dialog-footer">
				<el-button @click="downloadDialog.downloadVisible = false">Cancel</el-button>
				<el-button type="primary" @click="downloadShip">Confirm</el-button>
			</span>
			</template>
		</el-dialog>
	</el-card>
</template>

<script setup lang="ts">
import { useCrud } from '@/hooks'
import { reactive, ref } from 'vue'
import AddOrUpdate from './client-add-or-update.vue'
import FollowDate from './follow-date.vue'
import { IHooksOptions } from '@/hooks/interface'
import { getClientListApi, downloadShipment } from '@/api/client'
import { queryUserInfo } from '@/api/user'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { timestampToDateString } from '@/utils/tool'
const router = useRouter()

const state: IHooksOptions = reactive({
	dataListUrl: '/customerInfo/page',
	deleteUrl: '/customerInfo/delete',
	queryForm: {
		customerName: '',
		customerMobile: '',
		market: '',
		business: '',
		salesId: '',
		csId: ''
	}
})

// 销售、客服选项下拉
const salesOptions = ref([]), csOptions = ref([]);
const getUsersList = (type: string) => {
	let req = {
		page: 1,
		limit: 100,
		roleName: type
	}
	queryUserInfo(req).then(res => {
		switch(type){
			case 'SALES': salesOptions.value = res.data.list; break;
			case 'CS': csOptions.value = res.data.list; break;
		}
	})
}
getUsersList('SALES');
getUsersList('CS');


const downloadVisible = ref(false)
const downloadDialog = reactive({
	downloadVisible: false,
	createTime: [],
	salesId: '',
	csId: '',
})
const changeCreateTime = (val) =>{
	console.log(val)
}
var nowMonth = new Date().getMonth(); //当前月 
var nowYear = new Date().getFullYear(); //当前年 
//本月的开始时间
var monthStartDate = new Date(nowYear, nowMonth, 1); 
//本月的结束时间
var monthEndDate = new Date(nowYear, nowMonth+1, 0);

// downloadDialog.createTime = [timestampToDateString(monthStartDate, '-', false, false, true) + ' 00:00:00', timestampToDateString(monthEndDate, '-', false, false, true) + ' 23:59:59'] as any ;

downloadDialog.createTime = timestampToDateString(monthStartDate, '-', false, false, true) + ' 00:00:00';

const downloadShip = async () => {
	if(!downloadDialog.createTime || downloadDialog.createTime === ''){
		ElMessage.error('please choose create time 请先选择创建时间');
		return;
	}
	let end = downloadDialog.createTime.split(' ')[0] + ' 23:59:59';
	let lastDate = timestampToDateString(new Date(nowYear, Number(downloadDialog.createTime.split('-')[1]), 0), '-', false, false, true) + ' 23:59:59';
	let req = {
		createTimeBegin: downloadDialog.createTime,
		createTimeEnd: lastDate,
		salesId: downloadDialog.salesId,
		csId: downloadDialog.csId
	}
	// if(req.salesId === '' && req.csId === ''){
	// 	ElMessage.error('please choose a sales or cs 请先选择销售或客服');
	// 	return;
	// }
	const loading = ElLoading.service({
		lock: true,
		text: 'Loading',
		background: 'rgba(0, 0, 0, 0.7)',
	})
	let resData = await downloadShipment(req).then((response: any) => {
		return response
	})
	if(resData.data.code === 500){
		ElMessage.error(resData.data.msg);
		return;
	}
	if (resData) {
		const res = resData.data;
		const blob = new Blob([res]);//处理文档流
		const fileName = resData.headers['content-disposition'].split('=')[1];
		const down = document.createElement('a');
		down.download = fileName;
		down.style.display = 'none';
		down.href = URL.createObjectURL(blob);
		document.body.appendChild(down);
		down.click();
		URL.revokeObjectURL(down.href);  // 释放URL 对象
		document.body.removeChild(down); //下载完成移除
	} else {

	}
	loading.close();
}

const queryFormRef = ref();
const resetForm = () => {
	if(queryFormRef.value){
		queryFormRef.value.resetFields();
	}
}

const handleDownloadClose = (row: any) => {
	downloadDialog.downloadVisible = false
}

const addOrUpdateRef = ref()
const addOrUpdateHandle = (id?: Number) => {
	addOrUpdateRef.value.init(id)
}

const followDateRef = ref()
const followDateHandle = (id: any) => {
	router.push({path: '/followdate/clientDate', query: {clientId: id}})
}
const shortcuts = ref([
  {
    text: 'This month',
    value: [new Date(), new Date()],
  },
  {
    text: 'This year',
    value: () => {
      const end = new Date()
      const start = new Date(new Date().getFullYear(), 0)
      return [start, end]
    },
  },
  {
    text: 'Last 6 months',
    value: () => {
      const end = new Date()
      const start = new Date()
      start.setMonth(start.getMonth() - 6)
      return [start, end]
    },
  },
])

const { getDataList, sizeChangeHandle, selectionChangeHandle, sortChangeHandle, currentChangeHandle, deleteBatchHandle } = useCrud(state)
</script>
